<template>
    <div class="student_list_container">
        <el-dialog v-model="showAddModal" title="添加学生" width="500px" @close="closeModal">
            <el-form :model="addForm" label-width="80px">
                <el-form-item label="学生姓名" prop="name">
                    <el-input v-model="addForm.name" placeholder="请输入学生姓名" clearable @keyup.enter="confirmAddStudent" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeModal">取消</el-button>
                    <el-button type="primary" @click="confirmAddStudent" :loading="loading">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <div class="student_list">
            <div class="actions">
                <button @click="addStudent">添加学生</button>
                <button @click="deleteSelected">删除选中</button>
            </div>
            <table>
                <thead>
                    <tr>
                        <th>
                            <input type="checkbox" :checked="isAllSelected" @change="toggleSelectAll" />
                            全选
                        </th>
                        <th>序号</th>
                        <th>姓名</th>
                        <!-- <th>创建时间</th> -->
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="student in students" :key="student.student_id">
                        <td>
                            <input type="checkbox" :checked="selectedStudents.includes(student.student_id)"
                                @change="toggleStudentSelection(student.student_id)" />
                        </td>
                        <td>{{ student.student_id }}</td>
                        <td>{{ student.name }}</td>
                        <!-- <td>{{ student.create_time }}</td> -->
                        <td class="action-buttons">
                            <!-- <button @click="viewStudent(student)">查看</button> -->
                            <button @click="editStudent(student)">编辑</button>
                            <button @click="deleteStudent(student.student_id)">删除</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ApiService } from '@/api/apiService';
import { useUserStore } from '@/stores/user';
import { ElMessage, ElMessageBox } from 'element-plus'
const userStore = useUserStore();
const students = ref([]);

// const viewStudent = async (student) => {
//     const response = await ApiService.getStudent(student.student_id);
//     console.log('查看学生信息:', response.data.data);
// }

// 初始化数据
async function fetchItems() {

    const userId = userStore.getUser?.user_id;
    if (!userId) throw new Error('User ID not found');
    const response = await ApiService.getStudentsList(userId);
    if (response.status !== 200) {
        console.error('Failed to fetch items:', response.message);
        students.value = [];
    } else {
        students.value = response.data.data;

    }


}

onMounted(() => {
    fetchItems();
});
// 编辑学生
const editStudent = async (student) => {
    try {
        const { value: newName } = await ElMessageBox.prompt(
            '请输入新的姓名',
            '编辑学生',
            {
                confirmButtonText: '确认修改',
                cancelButtonText: '取消',
                inputPattern: /^.{2,20}$/,  // 限制2-20个字符
                inputErrorMessage: '姓名长度需在2-20个字符之间',
                inputValue: student.name,  // 默认显示原姓名
                inputType: 'text',
                customClass: 'edit-student-dialog'
            }
        )

        // 用户输入了新名字并确认
        const response = await ApiService.updateStudent(student.student_id, {
            name: newName.trim()  // 去除前后空格
        })

        if (response.status === 200) {
            ElMessage.success({
                message: '更新成功',
                duration: 2000
            })
            fetchItems() // 刷新学生列表
        } else {
            throw new Error(response.message || '更新失败')
        }
    } catch (error) {
        // 用户取消编辑或更新失败
        if (error !== 'cancel' && error !== 'close') {
            console.error('更新学生信息失败:', error)
            ElMessage.error({
                message: '更新学生信息失败: ' + (error.message || '请稍后重试'),
                duration: 3000
            })
        }
    }
}
// 选中的学生ID列表
const selectedStudents = ref([]);

// 是否全选
const isAllSelected = computed(() => {
    return students.value.length > 0 && students.value.every(student => selectedStudents.value.includes(student.student_id));
});

// 全选/取消全选
const toggleSelectAll = () => {
    if (isAllSelected.value) {
        selectedStudents.value = []; // 取消全选
    } else {
        selectedStudents.value = students.value.map(student => student.student_id); // 全选
    }
};

// 切换单个学生的选中状态
const toggleStudentSelection = (studentId) => {
    if (selectedStudents.value.includes(studentId)) {
        // 如果已选中，则取消选中
        selectedStudents.value = selectedStudents.value.filter(id => id !== studentId);
    } else {
        // 如果未选中，则选中
        selectedStudents.value.push(studentId);
    }
};

// 删除选中学生
const deleteSelected = async () => {
    console.log('Deleting students:', selectedStudents.value)

    // 检查是否已选择学生
    if (selectedStudents.value.length === 0) {
        ElMessage.warning('请选择要删除的学生')
        return
    }

    try {
        // 使用 Element Plus 确认框
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedStudents.value.length} 名学生吗？`,
            '删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: true,  // 允许HTML内容
            }
        )

        // 用户确认删除，调用API
        const response = await ApiService.deleteStudents(selectedStudents.value)
        if (response.status === 200) {
            ElMessage.success('删除成功')
            selectedStudents.value = []; // 清空选中项
            students.value = [];
            fetchItems() // 更新学生列表
            console.log('删除成功666666666')
        } else {
            throw new Error(response.message || '删除失败')
        }
    } catch (error) {
        // 用户取消删除或删除失败
        if (error !== 'cancel' && error !== 'close') {
            console.error('删除学生失败:', error)
            ElMessage.error('删除学生失败，请稍后重试')
        } else {
            ElMessage.info('已取消删除操作')
        }
    }
}

// 添加学生模态框状态
const showAddModal = ref(false);
const newStudentName = ref('');
// 添加学生表单
const addForm = ref({
    name: ''
})

const loading = ref(false)

// 打开添加对话框
const addStudent = () => {
    showAddModal.value = true
}

// 关闭对话框
const closeModal = () => {
    showAddModal.value = false
    addForm.value.name = ''
}

// 添加学生
const confirmAddStudent = async () => {
    if (!addForm.value.name.trim()) {
        ElMessage.warning('请输入学生姓名')
        return
    }

    loading.value = true
    try {
        const userId = userStore.getUser?.user_id
        if (!userId) throw new Error('未获取到用户ID')

        const response = await ApiService.addStudent({
            name: addForm.value.name.trim(),
            parent_id: userId
        })

        if (response.data.code === 200) {
            ElMessage.success({
                message: `添加成功！该学生的账号为: ${response.data.data.username} 密码: ${response.data.data.password}，您有1分钟的时间，请及时保存账户信息！！！`,
                duration: 1000 * 60 // 显示5秒，让用户有足够时间记录
            })
            closeModal()
            fetchItems()
        } else {
            throw new Error(response.message || '添加失败')
        }
    } catch (error) {
        ElMessage.error(`添加失败: ${error.message || '请稍后重试'}`)
    } finally {
        loading.value = false
    }
}
// 删除单个学生
// 删除单个学生
const deleteStudent = async (studentId) => {
    try {
        // 使用 Element Plus 确认框
        await ElMessageBox.confirm(
            '确定要删除该学生吗？此操作不可撤销！',
            '删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
                customClass: 'delete-confirm-box',
                confirmButtonClass: 'el-button--danger', // 红色确认按钮
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                        instance.confirmButtonLoading = true; // 显示加载状态
                        // 模拟异步操作
                        setTimeout(() => {
                            done();
                            instance.confirmButtonLoading = false;
                        }, 300);
                    } else {
                        done();
                    }
                }
            }
        );

        // 用户确认删除，调用API
        const response = await ApiService.deleteStudent(studentId);
        if (response.status === 200) {
            ElMessage.success({
                message: '删除成功',
                duration: 2000
            });
            fetchItems(); // 更新学生列表
        } else {
            throw new Error(response.message || '删除失败');
        }
    } catch (error) {
        // 用户取消删除或删除失败
        if (error !== 'cancel' && error !== 'close') {
            console.error('删除学生失败:', error);
            ElMessage.error({
                message: '删除学生失败，请稍后重试',
                duration: 3000
            });
        }
    }
};
</script>

<style scoped>
    @import url("@/assets/css/student_list.css");
</style>